package com.ujiuye.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ujiuye.mapper.MemberMapper;
import com.ujiuye.mapper.OrderMapper;
import com.ujiuye.mapper.OrdersettingMapper;
import com.ujiuye.mapper.SetmealMapper;
import com.ujiuye.pojo.Member;
import com.ujiuye.pojo.Order;
import com.ujiuye.pojo.Ordersetting;
import com.ujiuye.service.IOrderService;
import com.ujiuye.utils.DateUtils;
import com.ujiuye.utils.MessageConstant;
import com.ujiuye.utils.Result;
import com.ujiuye.vo.BusinessVo;
import org.apache.dubbo.config.annotation.Service;


import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 订单-会员下单预约检查 服务实现类
 * </p>
 *
 * @author zhangwenping
 * @since 2021-07-05
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {
    @Resource
    private OrdersettingMapper ordersettingMapper;
    @Resource
    private MemberMapper memberMapper;
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private SetmealMapper setmealMapper;

    @Override
    public Result order(Map<String, Object> order) {
        /*
        1、检查用户所选择的预约日期是否已经提前进行了预约设置，如果没有设置则无法进行 预约
        2、检查用户所选择的预约日期是否已经约满，如果已经约满则无法预约
        3、检查用户是否重复预约（同一个用户在同一天预约了同一个套餐），如果是重复预约 则无法完成再次预约
        4、检查当前用户是否为会员，如果是会员则直接完成预约，如果不是会员则自动完成注 册并进行预约
        5、预约成功，更新当日的已预约人数
         */
        String orderDate = (String) order.get("orderDate");
        String telephone = (String) order.get("telephone");
        String idCard = (String) order.get("idCard");
        String name = (String) order.get("name");
        int sexId = Integer.parseInt((String)order.get("sex"));
        Object setmealId = order.get("setmealId");

        //1、检查用户所选择的预约日期是否已经提前进行了预约设置，如果没有设置则无法进行预约
        QueryWrapper<Ordersetting> ordersettingQueryWrapper = new QueryWrapper<>();
        ordersettingQueryWrapper.eq("orderDate",orderDate);
        Ordersetting ordersetting = ordersettingMapper.selectOne(ordersettingQueryWrapper);
        if (ordersetting==null){//没有进行预约设置
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }
        //进行预约设置  2、检查用户所选择的预约日期是否已经约满，如果已经约满则无法预约
        if (ordersetting.getReservations()>=ordersetting.getNumber()){//约满
            return new Result(false, MessageConstant.ORDER_FULL);
        }
        //没有约满     3、检查当前用户是否为会员，如果是会员则直接完成预约，如果不是会员则自动完成注 册并进行预约
        QueryWrapper<Member> memberQueryWrapper = new QueryWrapper<>();
        memberQueryWrapper.eq("phoneNumber",telephone);
        memberQueryWrapper.eq("idCard",idCard);
        Member member = memberMapper.selectOne(memberQueryWrapper);
        if (member==null){//没有注册，自动注册
            member = new Member();
            member.setBirthday(getBirthday(idCard));//设置生日
            String sex = sexId == 1 ? "男" : "女";
            member.setSex(sex);//设置性别
            member.setPhonenumber(telephone);//设置电话
            member.setIdcard(idCard);//设置身份证
            member.setName(name);//设置姓名
            member.setRegtime(LocalDate.now());//设置注册时间
            member.setPassword("123456");//设置密码
            memberMapper.insert(member);
        }
        //获取会员id
        Integer memberId = member.getId();
        //检查用户是否重复预约（同一个用户在同一天预约了同一个套餐），如果是重复预约 则无法完成再次预约
        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.eq("member_id",memberId);
        orderQueryWrapper.eq("orderDate",orderDate);
        orderQueryWrapper.eq("setmeal_id",setmealId);
        Order sysOrder = orderMapper.selectOne(orderQueryWrapper);
        if (sysOrder!=null){//已经预约过
            return new Result(false,MessageConstant.HAS_ORDERED);
        }
        //没有预约，进行预约
        Order inOrder = new Order();
        //date转localDate
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate orderDate1 = LocalDate.parse(orderDate, dtf);
        inOrder.setOrderdate(orderDate1);
        inOrder.setMemberId(memberId);
        inOrder.setSetmealId(Integer.parseInt((String)setmealId));
        inOrder.setOrderstatus("未到诊");
        inOrder.setOrdertype("微信预约");
        orderMapper.insert(inOrder);
        //预约成功 更新已预约人数
        ordersetting.setReservations(ordersetting.getReservations()+1);
        ordersettingMapper.updateById(ordersetting);
        return new Result(true,MessageConstant.ORDER_SUCCESS);
    }

    @Override
    public List<Map<String, Object>> listSetmealCount() {
        return orderMapper.listSetmealCount();
    }

    //从身份证中提取生日
    public LocalDate getBirthday(String idCard){
        String year = idCard.substring(6, 10);
        String month = idCard.substring(10, 12);
        String day = idCard.substring(12, 14);
        String birthday = year+"/"+month+"/"+day;
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd");
        return LocalDate.parse(birthday,dtf);
    }

    @Override
    public BusinessVo getBusinessVo() {
        BusinessVo businessVo = new BusinessVo();
        businessVo.setHotSetmeal(setmealMapper.hotSetmeal());
        String dateString = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date());
        businessVo.setReportDate(dateString);
        businessVo.setTodayNewMember(todayNewMember());
        businessVo.setTotalMember(totalMember());
        businessVo.setThisWeekNewMember(thisWeekNewMember());
        businessVo.setThisMonthNewMember(thisMonthNewMember());
        businessVo.setTodayOrderNumber(todayOrderNumber());
        businessVo.setTodayVisitsNumber(todayVisitsNumber());
        businessVo.setThisWeekOrderNumber(thisWeekOrderNumber());
        businessVo.setThisWeekVisitsNumber(thisWeekVisitsNumber());
        businessVo.setThisMonthOrderNumber(thisMonthOrderNumber());
        businessVo.setThisMonthVisitsNumber(thisMonthVisitsNumber());
        return businessVo;
    }

    //本日新增会员
    public Integer todayNewMember(){
        int count = 0;
        try {
            String date = DateUtils.parseDate2String(new Date());
            QueryWrapper<Member> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("regTime",date);
            count = memberMapper.selectCount(queryWrapper);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return count;
    }

    //总会员数
    public Integer totalMember(){
        return memberMapper.selectCount(null);
    }

    //本周新增会员数
    public Integer thisWeekNewMember(){
        Date monday = DateUtils.getThisWeekMonday();
        QueryWrapper<Member> queryWrapper = new QueryWrapper<>();
        queryWrapper.ge("regTime",monday);
        return memberMapper.selectCount(queryWrapper);
    }

    //本月新增会员数
    public Integer thisMonthNewMember(){
        Date month = DateUtils.getFirstDay4ThisMonth();
        QueryWrapper<Member> queryWrapper = new QueryWrapper<>();
        queryWrapper.ge("regTime",month);
        return memberMapper.selectCount(queryWrapper);
    }

    //今日预约数
    public Integer todayOrderNumber(){
        int count = 0;
        try {
            String date = DateUtils.parseDate2String(new Date());
            QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("orderDate",date);
            count = orderMapper.selectCount(queryWrapper);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return count;
    }

    //今日到诊数
    public Integer todayVisitsNumber(){
        int count = 0;
        try {
            String date = DateUtils.parseDate2String(new Date());
            QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("orderDate",date);
            queryWrapper.eq("orderStatus","已到诊");
            count = orderMapper.selectCount(queryWrapper);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return count;
    }

    //本周预约数
    public Integer thisWeekOrderNumber(){
        Date monday = DateUtils.getThisWeekMonday();
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.ge("orderDate",monday);
        return orderMapper.selectCount(queryWrapper);
    }

    //本周到诊数
    public Integer thisWeekVisitsNumber(){
        Date monday = DateUtils.getThisWeekMonday();
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.ge("orderDate",monday);
        queryWrapper.eq("orderStatus","已到诊");
        return orderMapper.selectCount(queryWrapper);
    }

    //本月预约数
    public Integer thisMonthOrderNumber(){
        Date month = DateUtils.getFirstDay4ThisMonth();
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.ge("orderDate",month);
        return orderMapper.selectCount(queryWrapper);
    }

    //本月到诊数
    public Integer thisMonthVisitsNumber(){
        Date month = DateUtils.getFirstDay4ThisMonth();
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.ge("orderDate",month);
        queryWrapper.eq("orderStatus","已到诊");
        return orderMapper.selectCount(queryWrapper);
    }

}
